/**
 * Copyright 2011 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.google.solarchallenge.server.servlets.gwtservices;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.google.solarchallenge.client.rpc.AdminService;
import com.google.solarchallenge.server.domain.UserAccountDao;
import com.google.solarchallenge.server.persistence.PMF;
import com.google.solarchallenge.shared.dtos.UserAccountDto;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

/**
 * Server implementation for GWT RPC {@link AdminService}
 *
 * @author Arjun Satyapal
 */
public class AdminServiceImpl extends RemoteServiceServlet implements
    AdminService {

  @Override
  public ArrayList<UserAccountDto> getAllUserAccountDtos() {
    ArrayList<UserAccountDto> listOfDtos = new ArrayList<UserAccountDto>();

    PersistenceManager pm = PMF.getPersistenceManager();
    Query query = pm.newQuery(UserAccountDao.class);

    try {
      @SuppressWarnings("unchecked")
      List<UserAccountDao> listOfDao = (List<UserAccountDao>) query.execute();
      for (UserAccountDao currDao : listOfDao) {
        listOfDtos.add(currDao.toDto());
      }
    } catch (Throwable caught) {
      // TODO : Handle exception properly.
      caught.printStackTrace();
    } finally {
      query.closeAll();
      pm.close();
    }

    return listOfDtos;
  }

  @Override
  public void updateUserAccountDto(UserAccountDto dto) {
    PersistenceManager pm = PMF.getPersistenceManager();
    UserAccountDao dao = null;
    try {
      dao = pm.getObjectById(UserAccountDao.class, dto.getKey());
      if (dao == null) {
        throw new RuntimeException(
            "Approver with Id=" + dto.getKey() + " does not exist.");
      }

      dao = UserAccountDao.fromDto(dto, false/* isCreate */);
      pm.makePersistent(dao);
    } catch (Throwable caught) {
      // TODO : Handle exception properly.
      caught.printStackTrace();
    } finally {
      pm.close();
    }
  }
}
